<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/5/13 16:52
 */

namespace App\Logic\Goods;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use Illuminate\Database\Eloquent\Builder;
use App\Models\Store\Freight;;
use App\Models\Store\FreightRule;;
use App\Models\Store\Goods;
use Exception;
use Illuminate\Database\QueryException;
use Illuminate\Support\Arr;

class FreightLogic extends CommLogic
{
    
    /**
     * @param $params
     * @return mixed
     */
    public function lists($params)
    {
        $query = Freight::query()
            ->when(isset($params['status']), function (Builder $query) use ($params) {
                $query->where('status', $params['status']);
            })
            ->when(!empty($params['name']), function (Builder $query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }

        $data = $query->get()->toArray();
        return $data;
    }

    /**
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = Freight::query()
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', 'like', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }
        return $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])->toArray();
    }

    /**
     * @param $params
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model
     */
    public function store($params)
    {
        $lockName = 'freight_store_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        \DB::beginTransaction();
        try {
            $data = array(
                'name' => $params['name'],
                'ship_place' => $params['ship_place'],
                // 'status' => $params['status'],
                'freight_type' => $params['freight_type'],
                'postage_free' => implode(',', $params['postage_free']),
                'delivery_area' => implode(',', $params['delivery_area']) ?? '',
                'not_delivery' => implode(',', $params['not_delivery']) ?? '',
            );
            $freight = Freight::query()->create($data);
            if ($params['delivery_arr']) {
                $data = [];
                foreach($params['delivery_arr'] as $item){
                    $data[] = array(
                        'freight_id' => $freight->getQueueableId(),
                        'figure' => $item['figure'],
                        'freight_type' => $params['freight_type'],
                        'name' => $item['name'],
                        'amount' => $item['amount'] ?? 0,
                        'cond_figure' => $item['cond_figure'] ?? 0,
                        'increase_figure' => $item['increase_figure'] ?? 0,
                        'increase_amount' => $item['increase_amount'] ?? 0,
                    );
                }
                FreightRule::query()->insert($data);
            }
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new Exception($exception->getMessage(), $exception->getCode());
        }
        
        return true;
    }

    /**
     * @param $freightId
     * @return \App\Models\Model|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function show($data, $freightId)
    {
        $data = Freight::query()->where('id', $freightId)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '分类不存在！');
        $freight = $data->toArray();
        $freight['postage_free'] = explode(',', $freight['postage_free']);
        $freight['not_delivery'] = explode(',', $freight['not_delivery']);
        $freight['delivery_area'] = explode(',', $freight['delivery_area']);
        $delivery = FreightRule::query()->where('freight_id', $freight['id'])->get();
        foreach($delivery as &$item){
            $item['cond'] = $item['cond_figure'] > 0;
        }
        $freight['delivery_arr'] = $delivery;
        return $freight;
    }

    /**
     * @param $params
     * @param $freightId
     * @return bool|int
     */
    public function update($params, $freightId)
    {
        $lockName = 'freight_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        \DB::beginTransaction();
        try {
            $data = array(
                'name' => $params['name'],
                'ship_place' => $params['ship_place'],
                // 'status' => $params['status'],
                'freight_type' => $params['freight_type'],
                'postage_free' => implode(',', $params['postage_free']),
                'delivery_area' => implode(',', $params['delivery_area']) ?? '',
                'not_delivery' => implode(',', $params['not_delivery']) ?? '',
            );
            Freight::query()->where('id', $freightId)->update($data);
            FreightRule::query()->whereNotIn('id', array_column($params['delivery_arr'], 'id'))->delete();
            foreach($params['delivery_arr'] as $item){
                $data = array(
                    'freight_id' => $freightId,
                    'figure' => $item['figure'],
                    'freight_type' => $params['freight_type'],
                    'name' => $item['name'],
                    'amount' => $item['amount'] ?? 0,
                    'cond_figure' => $item['cond_figure'] ?? 0,
                    'increase_figure' => $item['increase_figure'] ?? 0,
                    'increase_amount' => $item['increase_amount'] ?? 0,
                );
                if (isset($item['id']) && !empty($item['id'])) {
                    FreightRule::query()->where('id', $item['id'])->update($data);
                } else {
                    FreightRule::query()->create($data);
                }
            }
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new Exception($exception->getMessage(), $exception->getCode());
        }

        return true;
    }

    /**
     * @param $id
     * @return bool|mixed|null
     */
    public function destroy($id)
    {
        $data = Freight::query()->where('id', $id)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '分类不存在！');
        \DB::beginTransaction();
        try {
            Freight::query()->where('id', $id)->delete();
            FreightRule::query()->where('freight_id', $id)->delete();
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }
}
